var cluster = require('cluster')
var http = require('http')
var numCPUs = require('os').cpus().length
if (cluster.isMaster) {
  console.log('Master process id is ', process.pid)

  // Fork workers
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork()
  }
  cluster.on('listening', (worker,address) => {
    var str = 'listening: worker ' + worker.process.pid +', Address: '+address.address+":"+address.port
    console.log(str)
  })
  cluster.on('exit', (worker, code, sigmal) => {
    console.log('worker process died, id ', worker.process.pid)
  })
} else {
  // worrker 可以共享同一个TCP连接
  http.createServer((req, res) => {
    res.writeHead(200)
    res.end('hello world\n')
  }).listen(8000)
  console.log('Worker start, process id ', process.pid)
}